package user

import (
	"context"
	"gitee.com/bobo-rs/idea-space-framework/framework/dao"
	"gitee.com/bobo-rs/idea-space-framework/framework/model"
	"gitee.com/bobo-rs/idea-space-framework/framework/service"
	"gitee.com/bobo-rs/idea-space-framework/pkg/exception"
	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/errors/gerror"
)

// SaveUser 保存用户详情-添加或编辑
func (u *sUser) SaveUser(ctx context.Context, item model.UserSaveUserDetailItem) (uint, error) {
	if item.User == nil {
		return 0, gerror.New(`缺少用户消息`)
	}
	err := dao.User.Transaction(ctx, func(ctx context.Context, tx gdb.TX) error {
		// 保存用户信息
		r, err := dao.User.Ctx(ctx).OmitEmpty().Save(item.User)
		if err != nil {
			return gerror.Wrapf(err, `保存用户失败%s`, err.Error())
		}

		// 获取用户ID
		uid, err := r.LastInsertId()
		if err != nil {
			return gerror.Wrapf(err, `创建用户失败%s`, err.Error())
		}
		item.UserDetail.UserId = uint(uid)

		// 保存用户详情
		_, err = dao.UserDetail.Ctx(ctx).OmitEmpty().Save(item.UserDetail)
		if err != nil {
			return gerror.Wrapf(err, `保存用户详情失败%s`, err.Error())
		}

		// 保存用户资金
		item.UserFunds.UserId = item.UserDetail.UserId
		_, err = dao.UserFunds.Ctx(ctx).OmitEmpty().Save(item.UserFunds)
		if err != nil {
			return gerror.Wrapf(err, `保存用户资金信息失败%s`, err.Error())
		}

		return nil
	})
	if err != nil {
		return 0, err
	}
	return item.UserDetail.UserId, nil
}

// UpdateUserNickname 更新用户昵称
func (u *sUser) UpdateUserNickname(ctx context.Context, uid uint, nickname string) error {
	if uid == 0 {
		return exception.New(`缺少用户ID`)
	}
	_, err := dao.User.Ctx(ctx).
		Where(dao.User.Columns().Id, uid).
		Data(dao.User.Columns().Nickname, nickname).
		Update()
	if err != nil {
		return exception.New(`更新昵称失败，请重试`)
	}
	return nil
}

// GetUserDetail 获取用户详情
func (u *sUser) GetUserDetail(ctx context.Context) *model.UserDetailItem {
	// 获取用户基础授权信息
	userAuth := service.BizCtx().GetUser(ctx)
	if userAuth == nil {
		return nil
	}
	detail := &model.UserDetailItem{
		Uid: userAuth.Uid,
		UserAccountNameItem: model.UserAccountNameItem{
			Nickname: userAuth.Nickname,
			Account:  userAuth.Account,
		},
	}

	// 用户详情
	detail.Detail = *u.GetUserAuthDetail(ctx)
	if detail.Detail.Nickname != detail.Nickname {
		detail.Nickname = detail.Detail.Nickname
	}
	return detail
}
